#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include<signal.h>

// 判断是否为内网ip
int is_internal_ip(const char *ip) {
    int a,b,c,d;
    if(sscanf(ip,"%d.%d.%d.%d",&a,&b,&c,&d) != 4) exit(0);
    if(a==10||a==172&&b==16||a==192&&b==168&&c==0) {
        return 0;
    }
    return 1;
}

// 报错处理
void print_html_err(int statusCode,char errorCause[0x20],char detailedError[256]) {
    printf("HTTP/1.1 %d %s\r\n\r\n",statusCode,errorCause);
    printf("<html><p>%s</p><html>",detailedError);
    exit(0);
}

// 发现外网请求
void hackfind(char a[0x10],const char *ip) {
    char command[1024];
    snprintf(command, sizeof(command), "echo '%s %s' >> ./index.html", a, ip);
    system(command);
    
    int num = strlen(ip) % 4;
    const char *Bologs[] = {"https://tysec.site/","https://www.cnblogs.com/Abyssun","https://blog.csdn.net/qq_61554462?type=sub&subType=fans","https://blog.csdn.net/qimingzhennan6?type=blog"};
    // 构造重定向响应（核心修改部分）
    printf("HTTP/1.1 302 Found\r\n");
    printf("Location: %s\r\n",Bologs[num]);
    printf("Content-Type: text/html\r\n");
    printf("\r\n");  // 空行分隔头与正文
    printf("<html><body>Redirecting to Bologs</body></html>\n");
    exit(0);
}

// 定时退出程序
void sig_alarm() {
    printf("Out Time over.\r\n");
    exit(0);
}

// 初始化程序
void init() {
    setvbuf(stdin, 0LL, 2, 0LL);
    setvbuf(stdout, 0LL, 2, 0LL);
    setvbuf(stderr, 0LL, 2, 0LL);
    signal(SIGALRM,sig_alarm);
    alarm(15);
    return;
}

// 主函数，实现逻辑
int main() {
    char buffer[4096];
    
    // 初始化关闭缓冲区并设置定时闹钟
    init();

    // 读取请求头（简化版，仅读取第一行）
    if (!fgets(buffer, sizeof(buffer), stdin)) return 1;
    
    // 解析请求方法和路径（路径在此示例中未实际使用）
    char method[16], path[256], proto[16];
    if (sscanf(buffer, "%15s %255s %15s", method, path, proto) != 3) {
        printf("HTTP/1.1 400 Bad Request\r\n\r\n");
        return 0;
    }

    // 只处理 GET 请求
    if (strcmp(method, "GET") != 0) {
        printf("HTTP/1.1 501 Not Implemented\r\n\r\n");
        return 0;
    }

    // 判断内网ip访问请求
    int hackattack = 1;
    const char *ip = "0.0.0.10";
    while (fgets(buffer, sizeof(buffer), stdin)&&strcmp(buffer,"\r\n")&&strcmp(buffer,"\n")) {
        const char *header_start = strstr(buffer,"X-Forword-For: ");
        if(header_start) {
            header_start += strlen("X-Forward-For: ");
            char *header_end = strstr(header_start,"\r\n");
            if(header_end || (header_end = strstr(header_start,"\n")) != 0) 
                *header_end = '\0';
            if(strlen(header_start)<7)
                print_html_err(400,"Bad Request","X-Forword-For len error.");
            hackattack = is_internal_ip(header_start);
            ip = header_start;
        }
        
    }
    if(hackattack&&*ip!=NULL)
        hackfind("I find you!",ip);
    
    // 过滤地址字符串
    if( strchr(path,'\\') || strstr(path,"..")) {
        print_html_err(400,"Bad Request","request path format error.");
    }

    // 尝试返回path请求地址
    char dest[0x10];
    char *header_end = strchr(path,'?');
    if(header_end != NULL)
        *header_end = '\0';
    strcpy(dest,path+1);
    FILE *file;
    file = fopen(dest, "r");
    if(file == NULL){
        print_html_err(400,"Bad Request","Not Fount. Filename Error.");
    }
    size_t bytesRead;
    while((bytesRead = fread(buffer, 1, sizeof(buffer), file)) > 0) {
        fwrite(buffer, 1, bytesRead, stdout);
    }
    fclose(file);

    // // 构造重定向响应（核心修改部分）
    // printf("HTTP/1.1 302 Found\r\n");
    // printf("Location: https://www.baidu.com\r\n");
    // printf("Content-Type: text/html\r\n");
    // printf("\r\n");  // 空行分隔头与正文
    // printf("<html><body>Redirecting to Baidu</body></html>\n");
    // fflush(stdout);

    return 0;
}